;
(function (call) {
    var dweather = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        latestTime: null,
        isFirstGetTime: true,
        router: {
            cfg: "/business/szyb/json/dweather.json",
            tccfg: "business/template/tc.html",
            procfg: '/monitor/getUserTodweatherProCfg.do',
            gridData: 'sjyb/getRdtRawData',
            getLatestTime: 'sjyb/rdtRawLatestTime',
            initStampPath: "/business/template/stamp.html",
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
        },
		//点击显示pdf技术说明
        showTechPdf:function(id,path){
            var that = this;
            if (CafeJS.ModalBoxExist(id)) {
                CafeJS.ModalBoxShow(id);
                return;
            }
            CafeJS.ModalBox({
                id: id,
                container: 'cafe-busis-container',
                title: "技术说明",
                width: 1300,
                height: 700,
                m_top: 70,
                m_right: 90,
                hasMask:true,
                hide: true,
                html: "<div id='"+id+"' style='width:100%;height:calc(100% - 10px)'></div>",
                showCall: function(obj) {
                    PDFObject.embed(path,"#"+id);
                },
                closed: function () { }
            });
        },
        // 获取最新起报时间
        getLatestTime: function (pro) {
            var that = this;
            that.isFirstGetTime = false;
            var param = {
                element: pro.ele_id,
                height: pro.height
            };
            $.ajax({
                url: this.router.getLatestTime,
                type: 'GET',
                dataType: 'json',
                async: false,
                data: param,
            }).done(function (res) {
                if (res.isSuccess) {
                    that.latestTime = res.data;
                    if (that.latestTime)
                        $("#ndDate").IDatePicker().setVal(that.latestTime);
                    that.buildLastTime();
                }
            })
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");

                    $('.product-dweather-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="ndDate" data-options="${item.dateOptions}" value="">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-dweather-datepicker .date-panel", {
                        query: function query() {
                            dweather.buildLastTime(function () {
                                dweather.getMultiGridData();
                            });
                        }
                    });
                    that.buildLastTime();
                    that.buildProContent(data.basic_pro[item.id] || []);
                })
                $(".product-dweather-tab ul").append($li);
            })
            $(".product-dweather-tab").show();
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-dweather-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);

                $item.append($title);

                if (item.content) {
                    if (!item.height) {
                        var $ul = $('<ul>');
                        item.content.forEach(function(pro) {
                            var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                            if (pro.selected)
                                $li.addClass("default");
                            $li.data('pro', pro);
                            if (pro.title)
                                $li.attr('title', pro.title);
                            if (pro.width)
                                $li.css("width", pro.width);
                            $ul.append($li);
                        })
                        $item.append($ul);
                    } else {
                        var $table = $('<table>');
                        var $thead = $('<tr>');
                        $thead.append('<th></th>');
                        item.height.forEach(function(h) {
                            $thead.append(`<th>${h}</th>`);
                        })
                        $table.append($thead);
                        item.content.forEach(function(pro) {
                            var $tr = $('<tr>');
                            $tr.append(`<td title=${pro.ele_name}>${pro.ele_name}</td>`);
                            item.height.forEach(function(h) {
                                var $td = $('<td>');
                                var newPro = $.extend({}, pro);
                                if(newPro.heights && -1 == $.inArray(h,newPro.heights)){
                                    $td.addClass("disabled");
                                }
                                newPro.height = h;
                                $td.data('pro', newPro);
                                $tr.append($td);
                            })
                            $table.append($tr);
                        })
                        $item.append($table);
                    }
                }
                $(".product-dweather-list").append($item);
            })
        },
        // 初始化最近起报时间
        buildLastTime: function (call) {
            var interval = $(".product-dweather-tab li.active").data("model").interval;
            var baseDate = $("#ndDate").IDatePicker().getVal() + ":00";
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                newDate.setHours(newDate.getHours() - interval);
            }
            $(".product-dweather-datechange ul").empty().append(liArr.reverse().join(""));

            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;

            var layers = that.getModels(pro.ele);
            var interval = Number($('.product-dweather-interval li.active').attr('interval')) * 60;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                pro: pro,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh',
                    timeInterval: 12,
                    customHm: [8, 20]
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function (pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);

                    that.getModelGridData(pro);
                },
                getPlayData: function (pro, timeArr) {
                    that.getModelGridData(pro, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
        // 初始化图例
        initLegentpicker: function (ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [];
            $.each(layers, function (i, m) {
                layerIds.push(m.id);
            });
            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                seq: 'decrease',
                productId: ele.color_id,
                isShowSlider: true
            });
        },
        // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function (pro) {
                var proInfo = that.getProInfo(pro);
                that.getModelGridData(proInfo);
            })
            var forecastTime = that.playList.getCurTime();
            var time = $("#ndDate").IDatePicker().getVal() + ":00";
            CafeJS.layerManage.updateLayerTime(time, 'dweather', forecastTime);
        },
        getModelGridData: function (proInfo, timeArr) {
            var that = this;
            if (!proInfo) return;

            var pro = proInfo.ele;
            var element = pro.ele_id;
            var queryTime = that.playList.getCurTime();
            var qbTime = proInfo.time;

            var agings = [],
                aging;
            if (timeArr) {
                timeArr.split(',').forEach(function (i) {
                    aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    aging = (Array(3).join('0') + aging).slice(-3);
                    agings.push(aging);
                })
                agings = agings.join(',');
            } else {
                agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                agings = (Array(3).join('0') + agings).slice(-3);
            }

            var height = pro.height != undefined ? pro.height : 0;
            qbTime = new Date(qbTime).format('yyyyMMddhhmmss');
            var params = {
                agings: agings,
                element: element,
                height: height,
                time: qbTime
            }
            CafeJS.ajax({
                url: that.router.gridData,
                params: params,
                type: "GET",
                success: function (e) {
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(pro);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        // 绘制格点色斑图
        drawGridRawMap: function (data, pro) {
            var typeArr = this.getModels(pro);
            var ele_id = pro.ele_id;
            var color_id = pro.color_id;
            var legentCfg = CafeJS.Legentconfig().cfg();
            var colorObj = legentCfg[color_id];

            // 显示色斑和数值
            GIS.GridShow.showByTypes_raw(this.mapId, typeArr, data, {}, colorObj);
            CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
        },
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "dweather-layer-" + m + "-" + pro.ele_id;
                if(pro.height){
                    layerId = layerId+pro.height;
                }
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function (proInfo) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid && !proInfo.ele.frames) {
                that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
            }
        },
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            if (pro.isGrid) {
                $(".product-dweather-list li.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })

                $(".product-dweather-list td.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })
            }

        },
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-dweather-list li.active,.product-dweather-list td.active").each(function () {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function (ele) {
            var name = ele.ele_name;
            var time = $("#ndDate").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'dweather',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function (proInfo) {
            var ele_id = proInfo.ele_id;
            if(proInfo.height){
                ele_id = ele_id + proInfo.height;
            }
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('dweather-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-dweather-list").off('click').on('click', 'li', function () {
                var pro = $(this).data('pro');
				if (pro.pdf_path) {
                    that.showTechPdf(pro.ele_id, pro.pdf_path);
                    return false;
                }
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);

                    that.clearGridLayer(pro);
                    that.removeLayer(pro);
                } else {
                    $(this).addClass("active");

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);

                    that.getModelGridData(proInfo);
                }
            }).on('click', 'td', function() {
                var pro = $(this).data('pro');
                if (!pro) return;
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);
                    that.clearGridLayer(pro);

                    that.removeLayer(pro);
                } else {
                    var prev = $(this).siblings('td.active');
                    if (prev.length > 0) {
                        prev.removeClass('active');
                        that.removeLayer(prev.data('pro'));
                        that.clearGridLayer(prev.data('pro'));
                    }

                    $(this).addClass("active");;
                    if(that.isFirstGetTime){
                        that.getLatestTime(pro);
                    }

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);
                    that.getModelGridData(proInfo);
                }
            })
            // 预报时间间隔
            $(".product-dweather-interval").delegate('li', 'click', function() {
                $(this).addClass("active").siblings().removeClass("active");
                var interval = Number($(this).attr('interval')) * 60;

                that.playList.init({
                    timeInterval: interval
                });

                that.getMultiGridData();
            })
            // 最近起报时间
            $(".product-dweather-datechange").delegate('li', 'click', function () {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');

                $("#ndDate").IDatePicker().setVal(time);

                that.playList.init({
                    curDate: time
                });

                that.getMultiGridData();
            })
            $('.product-dweather-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                $("#ndDate").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $("#ndDate").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $("#ndDate").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            });
            $(".product-dweather-tab li").first().click();
        }
    }
    if (typeof call === 'function') {
        CafeJS.dweather = dweather;
        call(dweather);
    }
    window.dweather = dweather;
})(function (dweather) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        dweather.init();
    });
});
